﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class WebMaster_Management : System.Web.UI.Page
{
    private readonly string m_FolderImage = GlobalClassBE.FolderPhotoData + @"Logon\";

    protected void Page_Load(object sender, EventArgs e)
    {
        LoadPage();
    }

    #region load page

    private void LoadPage()
    {
        string func = "";
        if (Request.Params[GlobalClassBE.MyUrlParameter.ActionName] != null)
            func = Request.Params[GlobalClassBE.MyUrlParameter.ActionName].ToString();

        pnlList.Visible = false;
        pnlAddEdit.Visible = false;
        pnlDelete.Visible = false;

        if (func == "" || func == "list")
        {
            pnlList.Visible = true;
            LoadList();
        }
        else if (func == "add" || func == "edit")
        {
            pnlAddEdit.Visible = true;
            LoadInput(func);
        }
        else if (func == "delete")
        {
            pnlDelete.Visible = true;
            LoadDelete();
        }

        GlobalClassBE.MyMessage.MgsCurrentTitle = GlobalClassBE.PageName.ManagementTitle;
    }

    private void LoadList()
    {
        int pageSize = GlobalClassBE.PageSize;
        DataTable dtData = GetDataSource("4");
        int k = 0;
        if (dtData != null)
            k = dtData.Rows.Count;
        this.gssPaging.PageCount = k / pageSize;
        if (this.gssPaging.PageCount * pageSize != k)
            this.gssPaging.PageCount += 1;
        this.grdData.PageSize = pageSize;
        this.gssPaging.PageSize = pageSize;
        this.gssPaging.ItemCount = k;
        if (this.gssPaging.CurrentIndex <= 0 || this.gssPaging.CurrentIndex > this.gssPaging.PageCount)
            this.gssPaging.CurrentIndex = 1;
        string[] astr = new string[1];
        GssDO.DOLogon DO = new GssDO.DOLogon();
        astr[0] = DO.PKIDLogonColumnName;
        GlobalClassBE.SetGridCss(this.grdData);
        this.ShowTextForList();
        this.grdData.AutoGenerateColumns = false;
        this.grdData.AllowPaging = true;
        this.grdData.DataKeyNames = astr;
        this.grdData.DataSource = dtData;
        this.grdData.DataBind();

        if (dtData == null || dtData.Rows.Count == 0)
            pnlData.Visible = false;
    }

    private void LoadInput(string actName)
    {
        ShowTextForInput();
        if (!Page.IsPostBack)
        {
            string sID = "";
            if (Request.Params["id"] != null)
                sID = Request.Params["id"].ToString();

            GlobalClassBE.MyMessage.MgsCurrentMessages = "";

            if (actName == "add")
                ShowToAdd();
            else if (actName == "edit")
            {
                if (sID != "")
                    ShowToEdit(sID);
                else
                {
                    GlobalClassBE.MyMessage.MgsCurrentMessages = GlobalClassBE.MyMessage.MgsEdit_Selected;
                    CancelPage();
                }
            }
            else
            {
                CancelPage();
            }
        }
    }

    private void LoadDelete()
    {
        string id = "";
        if (Request.Params["id"] != null)
            id = Request.Params["id"].ToString();

        GlobalClassBE.MyMessage.MgsCurrentMessages = "";

        if (id != "")
            ShowToDelete(id);
        else
            CancelPage();
    }

    #endregion load page

    #region show text

    private void ShowTextForList()
    {
        GssDO.DOLogon DO = new GssDO.DOLogon();
        Hashtable htb = new Hashtable();
        htb.Add(DO.UsernameColumnName, GlobalClassBE.GridText.Username);
        htb.Add("Fullname", GlobalClassBE.GridText.FullName);
        htb.Add("Email", GlobalClassBE.GridText.Email);
        htb.Add(DO.IsActiveColumnName, GlobalClassBE.GridText.IsActive);
        lkbAddNew.Text = GlobalClassBE.ActionText.Add;
        for (int i = 0; i < this.grdData.Columns.Count; i++)
        {
            if (this.grdData.Columns[i].GetType().Name == "CommandField")
            {
                if (((CommandField)this.grdData.Columns[i]).ShowEditButton)
                {
                    ((CommandField)this.grdData.Columns[i]).EditText = GlobalClassBE.ActionText.Edit;
                }
                if (((CommandField)this.grdData.Columns[i]).ShowDeleteButton)
                {
                    ((CommandField)this.grdData.Columns[i]).DeleteText = GlobalClassBE.ActionText.Delete;
                }
            }
            else if (this.grdData.Columns[i].GetType().Name == "ButtonField")
            {
                if (((ButtonField)this.grdData.Columns[i]).CommandName == "change")
                {
                    ((ButtonField)this.grdData.Columns[i]).Text = GlobalClassBE.GridText.ResetPassword;
                }
                if (((ButtonField)this.grdData.Columns[i]).CommandName == "profile")
                {
                    ((ButtonField)this.grdData.Columns[i]).Text = GlobalClassBE.GridText.EditProfile;
                }
            }
            else if (this.grdData.Columns[i].Visible)
            {
                string s = ((BoundField)this.grdData.Columns[i]).DataField;
                ((BoundField)this.grdData.Columns[i]).HeaderText = htb[s].ToString();
            }
        }
    }

    private void ShowTextForInput()
    {
        lblUsername.Text = GlobalClassBE.LabelText.Username;
        lblPassword.Text = GlobalClassBE.LabelText.Password;
        lblRePassword.Text = GlobalClassBE.LabelText.RePassword;
        lblEmail.Text = GlobalClassBE.LabelText.Email;
        lblFullname.Text = GlobalClassBE.LabelText.Fullname;

        reqFormatEmail.ErrorMessage = GlobalClassBE.MyMessage.InvalidEmailAddress;
        reqField.Text = GlobalClassBE.MyMessage.MgsRequiredField;

        btnSave.Text = GlobalClassBE.ButtonText.BtnSave;
        btnContinuous.Text = GlobalClassBE.ButtonText.BtnSaveCon;
        btnClear.Text = GlobalClassBE.ButtonText.BtnReset;
        btnCancel.Text = GlobalClassBE.ButtonText.BtnCancel;
    }

    private void ShowTextForDelete()
    {
        lblDelete.Text = GlobalClassBE.LabelText.DeleteConfirm;

        btnYes.Text = GlobalClassBE.ButtonText.BtnYes;
        btnNo.Text = GlobalClassBE.ButtonText.BtnNo;
    }

    #endregion show text

    #region load data

    private DataTable GetDataSource(string groupId)
    {
        DataTable dt = null;
        try
        {
            GssBL.BLLogon BL = new GssBL.BLLogon();
            dt = BL.getListByGroupId(groupId);
        }
        catch (Exception exc)
        {
            string mess = exc.Message.ToString();
            dt = null;
        }
        return dt;
    }

    #endregion load data

    #region SaveState
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        Page.RegisterRequiresControlState(this);
    }
    protected override object SaveControlState()
    {
        object[] state = new object[2];
        object baseState = base.SaveControlState();
        state[0] = baseState;
        state[1] = SelectedItemKeys;
        return state;
    }
    protected override void LoadControlState(object savedState)
    {
        if (savedState == null) return;
        if (savedState is object[])
        {
            object[] state = (object[])savedState;
            base.LoadControlState(state[0]);
            SelectedItemKeys = state[1];
        }
    }
    #endregion SaveState

    #region properties

    protected object m_ItemKeys;
    public virtual object SelectedItemKeys
    {
        get { return m_ItemKeys; }
        set { m_ItemKeys = value; }
    }
    #endregion properties

    /*    list    */

    protected void SelectedIndexChanged(int k)
    {
        this.grdData.SelectedIndex = k;
        m_ItemKeys = this.grdData.DataKeys[k].Value;
    }
    protected void gssPaging_Command(object sender, CommandEventArgs e)
    {
        int i = Convert.ToInt32(e.CommandArgument);
        this.gssPaging.CurrentIndex = i;
        this.grdData.PageIndex = i - 1;
        this.grdData.DataBind();
    }
    protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DataControlRowType itemType = e.Row.RowType;
        if (itemType == DataControlRowType.DataRow)
        {
            string s = ((BoundField)this.grdData.Columns[0]).DataField.ToString();
            if (DataBinder.Eval(e.Row.DataItem, s).ToString().CompareTo("&nbsp;") != 0)
            {
                // add event to rows item on grid
                try
                {
                    e.Row.Attributes.Add("onmouseover", "changeColorStyle(this);");
                    e.Row.Attributes.Add("onmouseout", "resetColorStyle(this);");
                }
                catch (Exception exc)
                {
                    string mess = exc.Message.ToString();
                }
            }
            string id = ((DataRowView)e.Row.DataItem).Row["IDLogon"].ToString();
            if (e.Row.Cells[4].Text.Trim() == "1")
                e.Row.Cells[4].Text = "<a href='ManagementActive.aspx?id=" + id + "'>Yes</a>";
            else
                e.Row.Cells[4].Text = "<a href='ManagementActive.aspx?id=" + id + "'>No</a>";
        }
    }
    protected void grdData_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int k = e.RowIndex;
        SelectedIndexChanged(k);
        string keys = (string)this.SelectedItemKeys;
        string sLink = String.Format(GlobalClassBE.URLFormat, GlobalClassBE.PageName.Management, "delete") + "&id=" + keys;
        Response.Redirect(sLink, false);
    }
    protected void grdData_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int k = e.NewEditIndex;
        SelectedIndexChanged(k);
        string keys = (string)this.SelectedItemKeys;
        string sLink = String.Format(GlobalClassBE.URLFormat, GlobalClassBE.PageName.Management, "edit") + "&id=" + keys;
        Response.Redirect(sLink, false);
    }
    protected void grdData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int k = Convert.ToInt32(e.CommandArgument);
        SelectedIndexChanged(k);
        string key = this.SelectedItemKeys.ToString();
        if (e.CommandName == "change")
        {
            Response.Redirect(@"ManagementChange.aspx?id=" + key);
        }
        if (e.CommandName == "profile")
        {
            Response.Redirect(@"ManagementProfile.aspx?id=" + key);
        }
    }
    protected void lkbAddNew_Click(object sender, EventArgs e)
    {
        string sLink = String.Format(GlobalClassBE.URLFormat, GlobalClassBE.PageName.Management, "add");
        Response.Redirect(sLink, false);
    }

    #region ShowAll

    private void ShowToAdd()
    {
        txtUsername.Text = "";
        txtPassword.Text = "";
        txtRePassword.Text = "";
        txtEmail.Text = "";

        lblActionName.Text = GlobalClassBE.ActionText.Add;
        ShowButton(true);
        GlobalClassBE.MyMessage.MgsCurrentMessages = "";
    }
    private void ShowToEdit(string pID)
    {
        try
        {
            GssDO.DOLogon DO = getByID(pID);

            if (DO != null)
            {
                //txtTitle.Text = DO.Title;
                //txtTitle_EN.Text = DO.Title_EN;
                //txtEmail.Text = DO.Email;
                //txtWebsite.Text = DO.Website;
                //txtLevel.Text = DO.Level.ToString();
                //txtDescription.Text = DO.Description;
                //txtDescription_EN.Text = DO.Description_EN;

                //lblTempID.Text = DO.PKIDPartner;
                //lblCurrentImages.Text = DO.Logo;
                //if (DO.Logo.Trim() != "")
                //{
                //    ckbDeleteImages.Visible = true;
                //    lblDeleteImages.Visible = true;
                //}
                //else
                //{
                //    ckbDeleteImages.Visible = false;
                //    lblDeleteImages.Visible = false;
                //}
                lblActionName.Text = GlobalClassBE.ActionText.EditPage;
                ShowButton(false);
                GlobalClassBE.MyMessage.MgsCurrentMessages = "";
            }
            else
            {
                GlobalClassBE.MyMessage.MgsCurrentMessages = GlobalClassBE.MyMessage.MgsEdit_Selected;
                CancelPage();
            }
        }
        catch (Exception exc)
        {
            string mess = exc.Message;
        }
    }
    private GssDO.DOLogon getByID(string id)
    {
        GssDO.DOLogon DO = null;
        try
        {
            GssBL.BLLogon BL = new GssBL.BLLogon();
            DO = BL.getLogonByID(id);
        }
        catch (Exception exc)
        {
            string mess = exc.Message.ToString();
            DO = null;
        }
        return DO;
    }
    /// <summary>
    /// show button on form (Parameter: true: show to add, false: show to edit)
    /// </summary>
    /// <param name="pFlag">type bool: true: show to add; false: show to edit</param>
    private void ShowButton(bool pFlag)
    {
        btnSave.Visible = true;
        btnClear.Visible = true;
        btnCancel.Visible = true;
        btnContinuous.Visible = pFlag;
    }
    private void CancelPage()
    {
        Response.Redirect(GlobalClassBE.PageName.Management, false);
    }
    private void ResetPage()
    {
        string actName = "";
        if (Request.Params[GlobalClassBE.MyUrlParameter.ActionName] != null)
            actName = Request.Params[GlobalClassBE.MyUrlParameter.ActionName].ToString();
        string sID = "";
        if (Request.Params["id"] != null)
            sID = Request.Params["id"].ToString();

        if (actName != "" && sID != "")
            Response.Redirect(String.Format(GlobalClassBE.URLFormat, GlobalClassBE.PageName.Management, "edit") + "&id=" + sID, false);
        else
            Response.Redirect(String.Format(GlobalClassBE.URLFormat, GlobalClassBE.PageName.Management, "add"), false);
    }
    private void SavePage(bool pFlag)
    {
        lblMessage.Text = "";
        if (validateForm())
        {
            string actName = "";
            if (Request.Params[GlobalClassBE.MyUrlParameter.ActionName] != null)
                actName = Request.Params[GlobalClassBE.MyUrlParameter.ActionName].ToString();
            if (actName == "add")
                SaveAdd(pFlag);
            else if (actName == "edit")
            {
                string sID = lblTempID.Text.ToString();
                if (sID != "")
                    SaveEdit(sID);
                else
                {
                    GlobalClassBE.MyMessage.MgsCurrentMessages = GlobalClassBE.MyMessage.MgsEdit_Selected;
                    CancelPage();
                }
            }
            else
            {
                CancelPage();
            }
        }
    }
    private void SaveAdd(bool pFlag)
    {
        try
        {
            GssDO.DOLogon DO = fillDO();
            GssDO.DOAssign DoAssign = fillDOAssign(DO.PKIDLogon);
            GssDO.DOMember DoMember = fillDOMember(DO.PKIDLogon);
            GssBL.BLLogon BL = new GssBL.BLLogon();
            BL.Insert(DO, DoAssign, DoMember);
            GlobalClassBE.MyMessage.MgsCurrentMessages = GlobalClassBE.MyMessage.MgsAdd_Success;
            if (!pFlag)
                CancelPage();
            else
                ResetPage();
        }
        catch (Exception exc)
        {
            string mess = exc.Message.ToString();
            lblMessage.Text = GlobalClassBE.MyMessage.MgsAdd_UnSuccess;
        }
    }
    private void SaveEdit(string pID)
    {
        try
        {
            GssDO.DOLogon DO = fillDO(pID);
            GssBL.BLLogon BL = new GssBL.BLLogon();
            bool b = false, bUpload = true, bDelete = true;
            //if (bUpload)
            //{
            //    if (ckbDeleteImages.Checked)
            //    {
            //        string strFileUpload = m_FolderImage + @"\" + lblCurrentImages.Text;
            //        bDelete = GlobalClassBE.DeleteFile(strFileUpload);
            //        if (!bDelete)
            //        {
            //            lblMessage.Text = GlobalClassBE.MyMessage.MgsAccess_Deny;
            //        }
            //    }
            //    else
            //    {
            //        if (fulImages.FileName.Trim() != "")
            //        {
            //            b = GlobalClassBE.UploadFile(fulImages, m_FolderImage, DO.Logo);
            //            if (!b)
            //            {
            //                lblMessage.Text = GlobalClassBE.MyMessage.MgsUpload_Fail + GlobalClassBE.getFileName(fulImages.FileName);
            //                bUpload = false;
            //            }
            //        }
            //    }
            //}
            if (bUpload && bDelete)
            {
                BL.Update(DO);
                GlobalClassBE.MyMessage.MgsCurrentMessages = GlobalClassBE.MyMessage.MgsEdit_Success;
                CancelPage();
            }
        }
        catch (Exception exc)
        {
            string mess = exc.Message.ToString();
            lblMessage.Text = GlobalClassBE.MyMessage.MgsEdit_UnSuccess;
        }
    }

    private bool validateByLabel()
    {
        bool result = true;
        try
        {
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
        return result;
    }
    private bool validateForm()
    {
        bool result = true;
        try
        {
            if (!reqUsername.IsValid)
                result = false;
            if (!reqPassword.IsValid)
                result = false;
            if (!reqRePassword.IsValid)
                result = false;
            if (!reqFormatEmail.IsValid)
                result = false;
            if (!reqFormatEmail.IsValid)
                result = false;
            if (result)
            {
                result = validateByLabel();
            }
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
        return result;
    }

    private GssDO.DOLogon fillDO()
    {
        string sID = GlobalClassBE.CreateGUI();
        GssDO.DOLogon DO = fillDO(sID);
        return DO;
    }

    private GssDO.DOLogon fillDO(string id)
    {
        GssDO.DOLogon DO = new GssDO.DOLogon();
        try
        {
            DO.PKIDLogon = id;
            DO.Username = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();
            password = GlobalClassBE.encodeMD5(password);
            DO.Password = password;
            DO.ActivationCode = "";
            DO.CreatedBy = Session["UserLogin"].ToString().ToLower();
            DO.CreatedDate = DateTime.Now;
            DO.IsActive = 0;
            DO.Level = 0;
            DO.IsDeleted = 0;
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
        return DO;
    }

    private GssDO.DOAssign fillDOAssign(string logonID)
    {
        GssDO.DOAssign DO = new GssDO.DOAssign();
        DO.PKIDAssign = GlobalClassBE.CreateGUI();
        DO.LogonID = logonID;
        DO.GroupID = "4";
        DO.Level = 0;
        DO.IsDeleted = 0;

        return DO;
    }

    private GssDO.DOMember fillDOMember(string logonID)
    {
        GssDO.DOMember DO = new GssDO.DOMember();
        DO.PKIDMember = GlobalClassBE.CreateGUI();
        DO.LogonID = logonID;
        DO.Fullname = txtFullname.Text.Trim();
        DO.Email = txtEmail.Text.Trim();
        DO.Birthday = DateTime.Now;
        DO.Address = "";
        DO.Sex = 0;
        DO.Phone = "";
        DO.Level = 0;
        DO.IsDeleted = 0;

        return DO;
    }

    #endregion ShowAll

    /***** Add Edit ******/
    protected void btnSave_Click(object sender, EventArgs e)
    {
        SavePage(false);
    }
    protected void btnContinuous_Click(object sender, EventArgs e)
    {
        SavePage(true);
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        ResetPage();
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        CancelPage();
    }

    #region delete

    private void ShowToDelete(string id)
    {
        lblActionName.Text = GlobalClassBE.ActionText.DeletePage;

        ShowTextForDelete();

        string deleteMessage = GlobalClassBE.MyMessage.DeletedPartnerConfirmMessage;

        GssDO.DOLogon DO = getByID(id);

        if (DO != null)
        {
            lblDeletedMessage.Text = String.Format(deleteMessage, DO.Username);
        }
        else
            CancelPage();
    }

    private void SaveDelete()
    {
        try
        {
            string id = "";
            if (Request.Params[GlobalClassBE.MyUrlParameter.ObjectIDName] != null)
                id = Request.Params[GlobalClassBE.MyUrlParameter.ObjectIDName].ToString();

            if (id != "")
            {
                GssDO.DOLogon DO = fillDODelete(id);
                GssBL.BLLogon BL = new GssBL.BLLogon();
                BL.Update(DO);
                GlobalClassBE.MyMessage.MgsCurrentMessages = GlobalClassBE.MyMessage.MgsDelete_Success;
                CancelPage();
            }
            else
                CancelPage();
        }
        catch (Exception exc)
        {
            string mess = exc.Message.ToString();
            lblMessage.Text = GlobalClassBE.MyMessage.MgsDelete_UnSuccess;
        }
    }

    private GssDO.DOLogon fillDODelete(string id)
    {
        GssDO.DOLogon DO = null;
        try
        {
            DO = getByID(id);
            DO.IsDeleted = 1;
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
        return DO;
    }
    #endregion delete
    protected void btnYes_Click(object sender, EventArgs e)
    {
        SaveDelete();
    }
    protected void btnNo_Click(object sender, EventArgs e)
    {
        CancelPage();
    }
}
